package org.abettor.pushbox.activity2;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.abettor.pushbox.R;
import org.abettor.pushbox.activity.OptionActivity;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.DownloadMsg;
import org.abettor.pushbox.download.ParaDownloadMsg;
import org.abettor.pushbox.model.LastTimeIdInterface;
import org.abettor.pushbox.model.MessageBoxBean;
import org.abettor.pushbox.model.SelfMessage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 站内短信箱的 activity
 * 
 * @author jzh
 * 
 */
public class SiteMessageBoxActivity extends AbstractListActivity {
	private DownloadMsg download;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(R.string.label_message);
		download = new DownloadMsg(this);
		this.getListView().setOnItemClickListener(
				new MessageListItemClickListenner());
	}

	// 点击的listenner
	private class MessageListItemClickListenner implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> l, View v, int position, long id) {
			MessageBoxBean bean = (MessageBoxBean)l.getItemAtPosition(position);
			Intent in = new Intent();
			Bundle extras = new Bundle();
			extras.putInt("_id", (int) bean.getId());
			in.putExtras(extras);
			in.setClass(SiteMessageBoxActivity.this, SiteMessageActivity.class);
			startActivity(in);
		}
	}

	// 更新消息的操作
	protected void alertMsg() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog dialog = builder.create();
		dialog.setTitle(R.string.msg);
		dialog.setMessage(this.getText(R.string.input_nickname_first));
		// 拦截back key
		dialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					Intent in = new Intent();
					in.setClass(SiteMessageBoxActivity.this,
							OptionActivity.class);
					startActivity(in);
					SiteMessageBoxActivity.this.finish();
					return true;
				}
				return false;
			}
		});
		dialog.setButton(DialogInterface.BUTTON_POSITIVE,
				this.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent in = new Intent();
						in.setClass(SiteMessageBoxActivity.this,
								OptionActivity.class);
						startActivity(in);
						SiteMessageBoxActivity.this.finish();
					}
				});
		dialog.show();
	}

	@Override
	protected UserMapAdapter createAdapter() {
		return new SiteMessageBoxAdapter(new LinkedList<LastTimeIdInterface>());
	}

	private class SiteMessageBoxAdapter extends UserMapAdapter {
		public SiteMessageBoxAdapter(List<LastTimeIdInterface> list) {
			super(list);
		}

		public void addMapUserBean(List<LastTimeIdInterface> toAdd) {
			if (toAdd == null) {
				return;
			}
			Date lastTime = getLastAccessTime();
			Iterator<LastTimeIdInterface> itr = toAdd.iterator();
			while (itr.hasNext()) {
				LastTimeIdInterface net = itr.next();
				remove(net.getId());
				if (lastTime == null || net.getTime().before(lastTime)) {
					resoveUserList.add(net);
				} else {
					resoveUserList.add(0, net);
				}
			}
		}

		private void remove(int id) {
			Iterator<LastTimeIdInterface> itr = resoveUserList.iterator();
			LastTimeIdInterface in = null;
			while (itr.hasNext()) {
				in = itr.next();
				if (in.getId() == id) {
					itr.remove();
				}
			}
		}

	}

	@Override
	protected View layoutView(int position, View convertView, ViewGroup parent,
			LastTimeIdInterface bean) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		final MessageBoxBean item = (MessageBoxBean) bean;
		LayoutInflater inflater = SiteMessageBoxActivity.this
				.getLayoutInflater();
		ViewGroup theParent = (ViewGroup) inflater.inflate(
				R.layout.site_mesagebox_activity_item, parent, false);
		TextView titleTextView = (TextView) theParent
				.findViewById(R.id.resolved_msg);
		TextView timeView = (TextView) theParent
				.findViewById(R.id.resolve_time);
		TextView summaryTextView = (TextView) theParent
				.findViewById(R.id.summary);
		titleTextView.setText(changeMsgToStr(item));
		summaryTextView.setText(item.getSummary());
		timeView.setText(sdf.format(item.getTime()));
		return theParent;
	}

	private String changeMsgToStr(MessageBoxBean bean) {
		String str = "";
		str += bean.getNickName();
		str += ("(" + bean.getUnreadCount() + "/" + bean.getTotalCount() + ")");
		if (bean.getUnreadCount() > 0) {
			str = str + "(" + this.getText(R.string.message_board_activity_unread) + ")";
		}
		return str;
	}

	@Override
	protected String loadContentFromNet(Date time) {
		SelfMessage self = Config.readSelfMessage(this);
		int size = userMapAdapter.getCount();
		String str = download.downMsgBoxStr(self.getNickName(), size
				+ Config.PAGESIZE);
		return str;
	}

	@Override
	protected int isHasMoreData(String content) {
		return ParaDownloadMsg.isHasMoreMsgBox(content);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected List paraData(String content) {
		return ParaDownloadMsg.paraMessageBox(content);
	}

	@Override
	protected boolean needDialog()
	{
		return true;
	}

}
